/**
 * 自动列举系统公开的API path。
 */
package com.siasun.vaemrd.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;

@RestController
public class ApiDetailsController {

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @GetMapping("/api/details")
    public List<Map<String, Object>> getApiDetails() {
        List<Map<String, Object>> apiDetailsList = new ArrayList<>();
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();

        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
            RequestMappingInfo mappingInfo = entry.getKey();
            HandlerMethod handlerMethod = entry.getValue();

            Map<String, Object> apiDetails = new HashMap<>();
            // 获取请求路径
            Set<String> patterns = mappingInfo.getPatternValues();
            apiDetails.put("paths", patterns);

            // 获取请求方法
            Set<RequestMethod> methods = mappingInfo.getMethodsCondition().getMethods();
            apiDetails.put("methods", methods);

            // 获取方法参数
            Method method = handlerMethod.getMethod();
            Parameter[] parameters = method.getParameters();
            List<Map<String, String>> paramDetails = new ArrayList<>();
            for (Parameter parameter : parameters) {
                Map<String, String> paramInfo = new HashMap<>();
                paramInfo.put("name", parameter.getName());
                paramInfo.put("type", parameter.getType().getName());
                paramDetails.add(paramInfo);
            }
            apiDetails.put("parameters", paramDetails);

            apiDetailsList.add(apiDetails);
        }

        return apiDetailsList;
    }
}